package com.qf.qfwemediagateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.qf.qfleadnewsutils.commons.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order(-1)
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse resp = exchange.getResponse();

        //放行一些和登录或者注册相关的
        String path = req.getURI().getPath();
        if (path.contains("/login/in")){
            //放行
            return chain.filter(exchange);
        }

        //获取token（兼容请求头中和请求路径中的token携带方式）
        String token = req.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            token = req.getQueryParams().getFirst("token");
            if (StringUtils.isBlank(token)){
                //没有携带，不能访问
                resp.setStatusCode(HttpStatus.UNAUTHORIZED);
                return resp.setComplete();
            }
        }

        //携带了token,对token进行验证
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int resut = AppJwtUtil.verifyToken(claims);

        if (resut == 1 || resut == 2){
            //不合法或者过期
            resp.setStatusCode(HttpStatus.UNAUTHORIZED);
            return resp.setComplete();
        }

        //放行，放行过去的是用户id（获取uid）
        Long uid = Long.parseLong(claims.get("id").toString());

        //允许访问(对原始的req对象中的头信息进行异构处理)
        req = req.mutate().headers(headers->{
            headers.set("uid",uid+"");
        }).build();

        //对exchange进行异构
        exchange = exchange.mutate().request(req).build();

        return chain.filter(exchange);
    }
}
